<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">
        {{ isLoginView ? "企航ERP系统 - 登录" : "企航ERP系统 - 注册" }}
      </h2>
      <el-form
        :model="activeForm"
        ref="registerForm"
        label-width="0"
        class="login-form"
      >
        <!-- 根据当前视图显示不同的表单项 -->
        <el-form-item>
          <el-input
            v-model="activeForm.UserName"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            :type="isLoginView ? 'password' : 'password'"
            v-model="activeForm.UserPWD"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!isLoginView">
          <el-input
            type="password"
            v-model="activeForm.confirmUserPWD"
            placeholder="请再次输入密码"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>

        <el-form-item v-if="!isLoginView">
          <div class="captcha">
            <span>{{ captcha.code }}</span>
            <el-button icon="el-icon-refresh" circle @click="generateCaptcha" />
          </div>
          <el-input
            v-model="captcha.input"
            placeholder="请输入验证码"
            @input="onCaptchaInput"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="login-btn" @click="handleSubmit">{{
            isLoginView ? "登录" : "注册"
          }}</el-button>
        </el-form-item>
      </el-form>

      <!-- 切换视图 -->
      <div class="form-switch" v-if="isLoginView">
        还没有账号？<a href="#" @click="switchToRegister">立即注册</a>
      </div>
      <div class="form-switch" v-else>
        已有账号？<a href="#" @click="switchToLogin">去登录</a>
      </div>
    </el-card>
  </div>
</template>

<script>
import $http from "@/routers/base";
export default {
  data() {
    return {
      //登录
      loginForm: {
        userId: "",
        UserName: "",
        UserPWD: "",
      },
      //注册
      registerForm: {
        UserName: "",
        UserPWD: "",
        confirmUserPWD: "", // 确认密码
      },
      captcha: {
        code: "", // 存储生成的验证码
        input: "", // 用户输入的验证码
        key: "", // 验证码的会话key
        timeout: null, // 验证码超时计时器
      },
      captchaInterval: null, // 验证码倒计时计时器
      isLoginView: true, // 控制当前视图是登录还是注册
    };
  },
  computed: {
    activeForm() {
      return this.isLoginView ? this.loginForm : this.registerForm;
    },
  },
  methods: {
    switchToLogin() {
      this.isLoginView = true;
    },
    switchToRegister() {
      this.isLoginView = false;
    },
    //登录
    async login() {
      const loadingInstance = this.$loading({
        lock: true,
        text: "正在登录，请稍候...",
        background: "rgba(0, 0, 0, 0.7)",
        target: ".login-container",
        duration: 0,
      });

      // 对表单进行验证，确保用户名和密码不为空
      if (!this.loginForm.UserName || !this.loginForm.UserPWD) {
        this.$message.error("用户名和密码都是必填项！");
        return;
      }

      try {
        const response = await $http.post("User/Login", {
          UserName: this.loginForm.UserName,
          UserPWD: this.loginForm.UserPWD,
        });
        localStorage.setItem("token", response.token);

        if (response) {
          this.$message.success("登录成功咯！");
          const token = response.token;
          localStorage.setItem("token", token); // 存储Token
          localStorage.setItem("username", this.loginForm.UserName);
          localStorage.setItem("uID", response.userId);
          console.log(response.userId);
          console.log(this.loginForm.UserName);
          console.log(token);
          setTimeout(() => {
            this.$router.push("/Main");
          }, 1500);
        } else {
          this.$message.error("登录失败,用户名或密码有误！");
        }
      } catch (error) {
        console.error("登录失败", error);
        this.$message.error("登录失败，请检查网络或联系管理员！");
      } finally {
        // 在请求结束后关闭 loading
        setTimeout(() => {
          loadingInstance.close();
        }, 500);
      }
    },
    //登录
    async handleSubmit() {
      if (this.isLoginView) {
        this.login();
      } else {
        this.register();
      }
    },

    //注册
    async register() {
      if (this.$refs.registerForm) {
        this.$refs.registerForm.validate(async (valid) => {
          if (valid) {
            if (!this.registerForm.UserName) {
              this.$message.error("用户名不能为空！");
              return;
            }
            if (this.registerForm.UserPWD.length < 6) {
              this.$message.error("密码长度不能少于6位！");
              return;
            }
            if (
              this.registerForm.UserPWD !== this.registerForm.confirmUserPWD
            ) {
              this.$message.error("注册失败：密码和确认密码不匹配！");
              return;
            }
            // 在发送注册请求之前验证验证码
            if (!this.checkCaptcha()) {
              this.$message.error("请先验证验证码！");
              return;
            }

            try {
              const exists = await this.checkUserNameExists(
                this.registerForm.UserName
              );
              if (exists) {
                this.$message.error("用户名已存在，请使用其他用户名注册！");
                return;
              } else {
                const response = await $http.post(
                  "User/Register",
                  this.registerForm
                );
                if (response.status == 200) {
                  this.$message.success("注册成功，请登录！");
                  this.switchToLogin();
                } else {
                  if (typeof response === "string") {
                    this.$message.error("注册失败：" + response);
                  } else {
                    this.$message.error(
                      "注册失败：" + JSON.stringify(response)
                    );
                  }
                }
              }
            } catch (error) {
              this.$message.error("注册失败，请检查网络或联系管理员！");
            }
          }
        });
      } else {
        console.log("registerForm is not defined");
      }
    },
    // 添加用于验证用户名是否存在的方法
    async checkUserNameExists(userName) {
      try {
        const response = await $http.get("CheckUserNameExists", {
          params: {
            userName: userName,
          },
        });
        return response.exists;
      } catch (error) {
        console.error("验证失败", error);
        throw error;
      }
    },

    // 生成新的验证码
    generateCaptcha() {
      const code = Math.random().toString(36).substr(2, 4); // 生成4位随机数作为验证码
      this.captcha.code = code;
      this.captcha.key = Date.now().toString(); // 使用当前时间戳作为会话key
      this.captcha.timeout = setTimeout(() => {
        this.captcha.code = "";
        this.captcha.key = "";
      }, 60000); // 验证码有效期设置为1分钟
    },

    // 检查用户输入的验证码是否正确
    checkCaptcha() {
      if (this.captcha.input && this.captcha.code) {
        return this.captcha.input === this.captcha.code;
      }
      return false;
    },

    // 清除验证码计时器
    clearCaptchaTimeout() {
      if (this.captcha.timeout) {
        clearTimeout(this.captcha.timeout);
        this.captcha.timeout = null;
      }
    },

    // 重置验证码
    resetCaptcha() {
      this.captcha.input = "";
      this.clearCaptchaTimeout();
    },

    // 发送验证码到后端进行验证
    verifyCaptcha() {
      if (this.checkCaptcha()) {
        this.$message.success("验证码验证成功！");
      } else {
        this.$message.error("验证码错误，请重试！");
      }
    },

    // 用户输入验证码后触发的方法
    onCaptchaInput() {
      if (this.captchaInterval) {
        clearInterval(this.captchaInterval); // 清除之前的倒计时
      }
      if (this.checkCaptcha()) {
        this.verifyCaptcha();
      } else {
        this.resetCaptcha();
        this.captchaInterval = setInterval(() => {
          const remainingTime = (this.captcha.timeout - Date.now()) / 1000;
          if (remainingTime <= 0) {
            this.resetCaptcha();
            clearInterval(this.captchaInterval);
          } else {
            this.$message.warning(
              `验证码剩余时间：${Math.floor(remainingTime / 60)}分${
                remainingTime % 60
              }秒`
            );
          }
        });
      }
    },
  },
};
</script>

<style scoped>
.form-switch {
  margin-top: 20px;
  text-align: center;
  color: #409eff;
  cursor: pointer;
  left: -600px;
}

.login-container {
  position: fixed;
  /* 确保容器覆盖整个屏幕 */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url("../Images/Snipaste_2024-03-26_11-44-46.png");
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0;
  padding: 0;
}

.login-card {
  width: 400px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  position: relative;
  left: -600px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
}

.login-form {
  width: 100%;
}

.login-btn {
  width: 100%;
  margin-top: 20px;
}

.signup-link {
  margin-top: 20px;
  text-align: center;
  color: #409eff;
}

.signup-link a {
  color: #409eff;
  text-decoration: none;
  cursor: pointer;
}

.signup-link a:hover {
  text-decoration: underline;
}

.captcha {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.captcha span {
  margin-right: 10px;
  font-weight: bold;
  color: #409eff;
}

.captcha button {
  margin-left: 10px;
}
</style>
